<template>
  <div class="admin-container">
    <admin-header />
    <admin-sidebar />
    <div class="admin-main">
      <div class="admin-content">
        <h1>商品管理</h1>
        
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="商品名称">
              <el-input v-model="filterForm.name" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item label="商品分类">
              <el-select v-model="filterForm.category" placeholder="请选择分类" clearable>
                <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card>
          <div class="table-toolbar">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><plus /></el-icon>
              添加商品
            </el-button>
            <el-button type="danger" :disabled="!selectedItems.length" @click="handleBatchDelete">
              <el-icon><delete /></el-icon>
              批量删除
            </el-button>
          </div>
          
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            v-loading="loading"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="价格" width="120">
              <template #default="{row}">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120">
              <template #default="{row}">
                {{ getCategoryText(row.category) }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{row}">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="180" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{row}">
                <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"  
              v-model:page-size="pageSize"       
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="50%"
      @closed="resetForm"
    >
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0" 
            :precision="2" 
            :step="0.1" 
            controls-position="right" 
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入商品描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdminHeader from '@/components/admin/AdminHeader.vue'
import AdminSidebar from '@/components/admin/AdminSidebar.vue'
import { Plus, Delete } from '@element-plus/icons-vue'

// 商品分类选项
const categoryOptions = [
  { value: 'books', label: '书籍' },
  { value: 'electronics', label: '电子产品' },
  { value: 'daily', label: '生活用品' },
  { value: 'others', label: '其他' }
]

// 商品状态选项
const statusOptions = [
  { value: 'selling', label: '出售中' },
  { value: 'sold', label: '已售出' },
  { value: 'off', label: '已下架' }
]

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }]
}

// 模拟数据
const generateMockData = () => {
  return Array.from({ length: 50 }, (_, i) => ({
    id: i + 1,
    name: `商品${i + 1}`,
    price: (Math.random() * 1000).toFixed(2),
    category: categoryOptions[Math.floor(Math.random() * categoryOptions.length)].value,
    stock: Math.floor(Math.random() * 100),
    status: statusOptions[Math.floor(Math.random() * statusOptions.length)].value,
    description: `这是商品${i + 1}的详细描述，这是一个非常不错的商品。`,
    createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString()
  }))
}

// 响应式数据
const filterForm = ref({
  name: '',
  category: '',
  status: ''
})

const productForm = ref({
  id: null,
  name: '',
  category: '',
  price: 0,
  stock: 0,
  status: 'selling',
  description: ''
})

const tableData = ref([])
const loading = ref(false)
const selectedItems = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('添加商品')
const productFormRef = ref(null)
const mockData = ref([])

// 计算属性
const filteredData = computed(() => {
  return mockData.value.filter(item => {
    return (
      (filterForm.value.name ? item.name.includes(filterForm.value.name) : true) &&
      (filterForm.value.category ? item.category === filterForm.value.category : true) &&
      (filterForm.value.status ? item.status === filterForm.value.status : true)
    )
  })
})

// 方法
const getStatusText = (status) => {
  const item = statusOptions.find(option => option.value === status)
  return item ? item.label : status
}

const getStatusType = (status) => {
  const map = {
    selling: 'success',
    sold: 'info',
    off: 'warning'
  }
  return map[status] || ''
}

const getCategoryText = (category) => {
  const item = categoryOptions.find(option => option.value === category)
  return item ? item.label : category
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filteredData.value.slice(start, end)
    total.value = filteredData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  filterForm.value = {
    name: '',
    category: '',
    status: ''
  }
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

const handleSelectionChange = (val) => {
  selectedItems.value = val
}

const showAddDialog = () => {
  dialogTitle.value = '添加商品'
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  dialogTitle.value = '编辑商品'
  productForm.value = { ...row }
  dialogVisible.value = true
}

const resetForm = () => {
  productFormRef.value?.resetFields()
  productForm.value = {
    id: null,
    name: '',
    category: '',
    price: 0,
    stock: 0,
    status: 'selling',
    description: ''
  }
}

const submitForm = async () => {
  try {
    await productFormRef.value.validate()
    
    if (productForm.value.id) {
      // 编辑商品
      const index = mockData.value.findIndex(item => item.id === productForm.value.id)
      if (index !== -1) {
        mockData.value[index] = { ...productForm.value }
      }
      ElMessage.success('商品更新成功')
    } else {
      // 添加商品
      const newId = mockData.value.length ? Math.max(...mockData.value.map(item => item.id)) + 1 : 1
      const newProduct = {
        ...productForm.value,
        id: newId,
        createTime: new Date().toLocaleString()
      }
      mockData.value.unshift(newProduct)
      ElMessage.success('商品添加成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    mockData.value = mockData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (!selectedItems.value.length) return
  
  ElMessageBox.confirm(`确定要删除选中的${selectedItems.value.length}个商品吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedItems.value.map(item => item.id)
    mockData.value = mockData.value.filter(item => !selectedIds.includes(item.id))
    selectedItems.value = []
    ElMessage.success('批量删除成功')
    loadData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化
onMounted(() => {
  mockData.value = generateMockData()
  total.value = mockData.value.length
  loadData()
})
</script>

<style scoped>
.admin-container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.admin-main {
  margin-left: 220px;
  padding-top: 60px;
  height: 100%;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.admin-content {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-toolbar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.el-input-number {
  width: 100%;
}
</style>